import Monitors from './monitor';
import MinerRunningHolder from './MinerRunningHolder';

export default class ControlCenter {
    constructor(config) {
        this.config = config;
        this.monitors = new Array();
        this.blockQueue = new Map();
        Monitors.forEach(Clazz => {
            const monitor = new Clazz(config);
            const info = monitor.info();
            info.isRunning = false;
            info.hasNewBlock = false;
            this.monitors.push(monitor);
            this.blockQueue.set(info.name, info);
        });
        this.miners = config.miner.filter(min => min.enable).map(min => new MinerRunningHolder(min));
    }

    init() {
        this.monitors.forEach(monitor => {
            const name = monitor.info().name;
            monitor.addListener(blocks => {
                if (blocks.size > 0) {
                    console.log(`矿池 【${name}】 产出块 ${blocks.size} 个！`);
                    this.blockQueue.get(name).hasNewBlock = true;
                } else {
                    this.blockQueue.get(name).hasNewBlock = false;
                }
                this.handle();
            });
            monitor.start();
        });
        this.miners.forEach(miner => miner.start());
    }

    switchPool(name) {
        this.miners.forEach(miner => {
            if (name === 'default') {
                miner.switchToDefault();
            } else {
                miner.switchOnCommand();
            }
        });
    }

    handle() {
        const values = this.blockQueue.values();
        const queue = new Array();
        let next = values.next();
        while (!next.done) {
            if (next.value.hasNewBlock)
                queue.push(next.value);
            next = values.next();
        }

        if (queue.length === 0) {
            this.switchPool('default');
            return;
        }

        queue.sort((o1, o2) => {
            return o2.priority - o2.priority;
        });
        if (!queue[0].isRunning) {
            this.switchPool(queue[0].name);
        }
    }
}